import re #引入正则表达式模块

from urllib import request #导入网络请求模块

class Spider():
    url = "https://www.panda.tv/cate/lol"
    #正则表达式，匹配根节点中所有内容
    root_pattern = '<div class="video-info">([\s\S]*?)</div>'
     #正则表达式，匹配名字
    name_pattern = '</i>([\s\S]*?)</span>'
    #正则表达式，匹配观看人数
    number_pattern = '<span class="video-number">([\s\S]*?)</span>'

    def __fetch_content(self):
        r = request.urlopen(Spider.url) #通过url获取服务器返回html
        htmls = r.read()
        htmls = str(htmls, encoding='utf-8') #把字符数组转为str
        # print(type(htmls))
        return htmls
       
    #html分析函数，匹配需要的信息
    def __analysis(self,htmls):
           root_html = re.findall(Spider.root_pattern,htmls) #找到所有根节点
           anchors = [] #字典，用于保存所有名字与人数
           for html in root_html:
               name = re.findall(Spider.name_pattern,html)
               number = re.findall(Spider.number_pattern,html)
               anchor = {'name':name, 'number':number}
               anchors.append(anchor)
           #print(root_html[0]) #调试
        #    print(anchors[0]) #调试
           return anchors
          

    #数据精炼
    def __refine(self,anchors):
        l = lambda anchor:{
            'name':anchor['name'][0].strip(),#去除空格换行符
            'number':anchor['number'][0]
            }
        return map(l,anchors)

    #排序函数
    def __sort(self,anchors):
        anchors = sorted(anchors,key=self.__sort_seed,reverse=True)
        return anchors
    
    #比较器
    def __sort_seed(self,anchor):
        r = re.findall('\d*',anchor['number'])
        number = float(r[0])
        if '万' in anchor['number']:
            number *= 10000
        return number 

    #数据展示函数
    def __show(self,anchors):
        for rank in range(0,len(anchors)):
            print(str(rank+1)+':  ' + anchors[rank]['name'] + '---' + anchors[rank]['number'])
        

    def go(self):
        #获取服务器返回HTML数据
        htmls = self.__fetch_content()
       
        #正则表达式匹配信息
        anchors = self.__analysis(htmls)

         #精炼信息
        anchors = list(self.__refine(anchors))

        #排序
        anchors = self.__sort(anchors)
        
        #数据展示
        self.__show(anchors)

spider = Spider()
spider.go()